package com.cdtye.shuoh.controller.play;

import com.cdtye.shuoh.config.gb28181.transmit.callback.DeferredResultHolder;
import com.cdtye.shuoh.config.gb28181.transmit.callback.RequestMessage;
import com.cdtye.shuoh.config.gb28181.transmit.cmd.impl.SIPCommander;
import com.cdtye.shuoh.domain.device.entity.Device;
import com.cdtye.shuoh.service.device.DeviceChannelService;
import com.cdtye.shuoh.service.device.DeviceService;
import com.cdtye.shuoh.util.text.XmlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import javax.sip.InvalidArgumentException;
import javax.sip.SipException;
import javax.sip.message.Response;
import java.text.ParseException;

/**
 * GB28181 云台控制
 * @author ZhongWang Wang
 * @date 2022-12-21
 */
@RestController
@RequestMapping(value = "/ptz")
@ConditionalOnProperty(value = "sip.enabled", havingValue = "true")
public class PtzController {
    private final static Logger logger = LoggerFactory.getLogger(PtzController.class);

    @Autowired
    private SIPCommander cmder;

    @Autowired
    private DeferredResultHolder resultHolder;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceChannelService deviceChannelService;

    /***
     * 云台控制
     * @param deviceIdentification 设备id
     * @param channelId 通道id
     * @param command		指令码
     * @param horizonSpeed	水平移动速度
     * @param verticalSpeed	垂直移动速度
     * @param zoomSpeed	    缩放速度
     * @return String 控制结果
     */
    @GetMapping("/ptzCamera")
    public ResponseEntity<String> ptzCamera(String deviceIdentification,String channelId, String command, int horizonSpeed,int verticalSpeed,int zoomSpeed){
        logger.info(String.format("设备云台控制 API调用，deviceIdentification：%s ，channelId：%s ，command：%d ，horizonSpeed：%d ，verticalSpeed：%d ，zoomSpeed：%d",deviceIdentification, channelId, command, horizonSpeed, verticalSpeed, zoomSpeed));
        Device device = deviceService.findOneByDeviceIdentification(deviceIdentification);
        int cmdCode = 0;
        switch (command){
            case "left":
                cmdCode = 2;
                break;
            case "right":
                cmdCode = 1;
                break;
            case "up":
                cmdCode = 8;
                break;
            case "down":
                cmdCode = 4;
                break;
            case "upleft":
                cmdCode = 10;
                break;
            case "upright":
                cmdCode = 9;
                break;
            case "downleft":
                cmdCode = 6;
                break;
            case "downright":
                cmdCode = 5;
                break;
            case "zoomin":
                cmdCode = 16;
                break;
            case "zoomout":
                cmdCode = 32;
                break;
            case "stop":
                break;
            default:
                break;
        }
        cmder.frontEndCmd(device, channelId, cmdCode, horizonSpeed, verticalSpeed, zoomSpeed);
        return new ResponseEntity<String>("success", HttpStatus.OK);
    }

    /**
     * 通用前端控制命令API接口
     *
     * @param deviceIdentification
     * @param channelId
     * @param cmdCode
     * @param parameter1
     * @param parameter2
     * @param combindCode2
     * @return
     */
    @PostMapping("/frontEndCommand")
    public ResponseEntity<String> frontEndCommand(String deviceIdentification,String channelId,int cmdCode, int parameter1, int parameter2, int combindCode2){

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("设备云台控制 API调用，deviceIdentification：%s ，channelId：%s ，cmdCode：%d parameter1：%d parameter2：%d",deviceIdentification, channelId, cmdCode, parameter1, parameter2));
        }
        Device device = deviceService.findOneByDeviceIdentification(deviceIdentification);
        cmder.frontEndCmd(device, channelId, cmdCode, parameter1, parameter2, combindCode2);
        return new ResponseEntity<String>("success",HttpStatus.OK);
    }

    /**
     * 预置位查询命令API接口
     *
     * @param deviceIdentification
     * @param channelId
     * @return
     */
    @GetMapping("/presetQuery")
    public DeferredResult<ResponseEntity<String>> presetQueryApi(String deviceIdentification, String channelId) {
        if (logger.isDebugEnabled()) {
            logger.debug("设备预置位查询API调用");
        }
        Device device = deviceService.findOneByDeviceIdentification(deviceIdentification);
        cmder.presetQuery(device, channelId, event -> {
            Response response = event.getResponse();
            RequestMessage msg = new RequestMessage();
            msg.setId(DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + (XmlUtil.isEmpty(channelId) ? deviceIdentification : channelId));
            msg.setData(String.format("获取设备预置位失败，错误码： %s, %s", response.getStatusCode(), response.getReasonPhrase()));
            resultHolder.invokeResult(msg);
        });
        DeferredResult<ResponseEntity<String>> result = new DeferredResult<ResponseEntity<String >> (3 * 1000L);
        result.onTimeout(()->{
            logger.warn(String.format("获取设备预置位超时"));
            // 释放rtpserver
            RequestMessage msg = new RequestMessage();
            msg.setId(DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + (XmlUtil.isEmpty(channelId) ? deviceIdentification : channelId));
            msg.setData("获取设备预置位超时");
            resultHolder.invokeResult(msg);
        });
        resultHolder.put(DeferredResultHolder.CALLBACK_CMD_PRESETQUERY + (XmlUtil.isEmpty(channelId) ? deviceIdentification : channelId), result);
        return result;
    }
}
